<?php

namespace app\listing\logic;

use app\data\util\MqQueueName;
use app\listing\validate\ProductAdd;
use app\listing\validate\ProductEdit;
use app\systems\logic\MqTaskPushLogic;
use app\order\logic\OrderBtLogic;
use think\facade\Db;

class ListingLogic extends BasicLogic
{


    /**
     * @desc    在线产品列表
     * @author  luckyXiong
     * @date    2024-12-24
     */
    public function getProductList($params=[]){
        $limit                = getIsset($params,'limit',10);
        $spu                  = getIsset($params,'spu');
        $product_type         = getIsset($params,'product_type');
        $product_variant_type = getIsset($params,'product_variant_type');
        $product_title        = getIsset($params,'product_title');
        $created_time         = getIsset($params,'create_time');
        $where = [];
        $order = [];
        if($spu){
            $where[] = ['spu', 'like', '%' . $spu . '%'];
        }

        if (!empty($created_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($created_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($created_time[1]) + 3600*24-1)];
        }

        if($product_type){
            $where[] = ['product_type', '=',$product_type];
        }

        if($product_title){
            $where[] = ['product_title', 'like', '%' . $product_title . '%'];
        }

        if($product_variant_type){
            $where[] = ['product_variant_type', '=',$product_variant_type];
        }

        $order['create_time'] = 'desc';

        $field = '*';
        $res   = Db::name('listing_product')
            ->field($field)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $list = $res->items()?:[];
        $arr = [];

        $product_attr_type = Db::name('product_attr_level')->field('type_id,type_name')->where(['parent_id'=>0])->select()->toArray();
        $type_ids          = array_column($product_attr_type,null,'type_id');
        foreach($list as $k=>$v){
            $product_types            = $type_ids[$v['product_type']]??[];
            $arr[$k]['id']            = $v['id'];
            $product_images           = $v['product_images'] ? json_decode($v['product_images'],true) :'';
            if(is_array($product_images)){
                $current_images           = current($product_images);
            }else{
                $current_images           = $product_images;
            }

            $basic_image              = $current_images['src']??'';
            $arr[$k]['basic_image']   = $basic_image;
            $arr[$k]['spu']           = $v['spu'];
            $arr[$k]['product_title'] = $v['product_title'];
            $arr[$k]['product_variant_type_value'] = $v['product_variant_type']== '1' ? '单品' :'多变体';
            $arr[$k]['product_type_value'] = $product_types['type_name']??'';
            $arr[$k]['create_time']   = $v['create_time'];
            $arr[$k]['update_time']   = $v['update_time'];
            $arr[$k]['supply_url']    = $v['supply_url'];
        }

        $data = [
            'list'   => $arr,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }



    /**
     * @desc    获取sku详情
     * @author  luckyXiong
     * @date    2024-12-29
     */
    public function get_sku_list($params=[]){
           $id    = $params['id']??'';
           $limit = $params['limit']??10;
           $page  = $params['page']??1;
           $field = 'id,spu,variant_json,product_variant_type,product_images,options';
           $list  = Db::name('listing_product')->field($field)->where(['id'=>$id])->find();
           $variant_json = json_decode($list['variant_json'],true);
           $arr    = [];



           foreach($variant_json as $k=>$v){
               $arr[$k]['id']           = $k+1;
               $arr[$k]['image_url']    = $v['image_url']??'';
               $arr[$k]['sku']          = $v['sku']??'';
               $arr[$k]['price']        = $v['price']??'';
               $arr[$k]['inventory_quantity']= $v['inventory_quantity']??'0';
               $arr[$k]['weight']       = $v['weight']??'';
           }
          $result = paginateArray($arr,$page, $limit);
          $list = [
              'list'  => $result['data'],
              'total' => $result['total'],
          ];
          return  $this->jsonMessage(200,true,'获取成功',$list);
    }



    /**
     * @desc    获取出单店铺信息
     * @author  luckyXiong
     * @date    2024-12-24
     */
    public function getListingShop($params=[]){
        $name     = $params['name']??'';
        $where    = [];
        $where[]  = ['id','<>',3];
        if($name){
            $name    = trim($name);
            $where[] = ['name', 'like', '%' . $name . '%'];
        }
        $field    = 'id as shop_id,name as shop_name,myshopify_domain';
        $list     = Db::name('shops')->field($field)->where($where)->select()->toArray();
        return $this->jsonMessage(200, true,'获取成功', $list);
    }


    /**
     * @desc    获取Collections
     * @author  luckyXiong
     * @date    2024-12-24
     */
    public function get_collections($params=[]){
        $shop_id  = $params['shop_id']??'';
        $name     = $params['name']??'';
        $where    = [];
        if(!$shop_id){
            return  $this->jsonMessage(201,false,'店铺ID不能为空!',null);
        }
        if($name){
            $name    = trim($name);
            $where[] = ['collection', 'like', '%' . $name . '%'];
        }
        $where[]  = ['shop_id', '=', $shop_id];
        $field    = 'id,shop_id,collection';
        $list     = Db::name('shops_collection')->field($field)->where($where)->select()->toArray();
        return $this->jsonMessage(200, true,'获取成功', $list);
    }


    /**
     * @desc    同步产品信息到店铺
     * @author  luckyXiong
     * @date    2024-12-26
     */
    public function syncListShop($params=[]){
          $product_ids  = $params['product_ids'] ??[];
          $shop_ids     = $params['shop_ids']    ??[];
          if(!$product_ids){
              return  $this->jsonMessage(201,false,'同步产品ID不能为空!',null);
          }
          $product_id = current($product_ids);
          if(!$shop_ids){
            return    $this->jsonMessage(201,false,'同步店铺ID不能为空!',null);
         }

         foreach($shop_ids as $v){
                      //推动数据到队列;
                      MqTaskPushLogic::mq_task_push(
                          '',
                          MqQueueName::QUEUE_PRODUCT_TO_SHOP_QUEUE,
                          [
                              'product_id'=>$product_id,
                              'shop_id'   =>$v
                          ],
                          false
                      );
         }
         //直接触发MQ消费 2024-11-30
         (new OrderBtLogic())->getCrontab();
         return json(DefaultResponse(200, true, '操作成功', ''));
    }




    /**
     * @desc    新增产品接口
     * @date    2024-11-23
     * @author  luckyXiong
     */
    public function add_product($params=[]){
        //验证器参数验证
        $validate    = new ProductAdd();
        $res         = $validate->check($params);
        if(!$res) return $this->jsonMessage(201, false, $validate->getError(), null);
        $spu                  =  $params['spu']??'';
        $product_variant_type =  $params['product_variant_type']??'';

        $product_title        =  $params['product_title']??'';
        $product_tags         =  $params['product_tags']??'';
        $product_desc         =  $params['product_desc']??'';

        $product_type         =  $params['product_type']??'';
        $supply_url           =  $params['supply_url']??'';
        $product_images       =  $params['product_images']??'';
        $options              =  $params['options']??'';
        $variant_json         =  $params['variant_json']??'';

        if($product_variant_type ==2 && !$variant_json){
            return  $this->jsonMessage(201,false,'产品变种类型不能为空!',null);
        }
        $images            =  $product_images ? current($product_images) :'';
        //主表数据写入
        $product_insert = [
                'spu'                      => trim($spu),
                'product_variant_type'     => $product_variant_type,
                'product_tags'             => trim($product_tags),
                'product_title'            => trim($product_title),
                'product_desc'             => trim($product_desc),
                'product_type'             => trim($product_type),
                'supply_url'               => trim($supply_url),
                'product_images'           => $product_images ? json_encode($product_images):'',
                'options'                  => $options        ? json_encode($options):'',
                'variant_json'             => $variant_json   ? json_encode($variant_json):'',
                'create_time'              => date("Y-m-d H:i:s", time()),
                'update_time'              => date("Y-m-d H:i:s", time()),
            ];
            $weight = '';
            if($variant_json){
                $current_variant = current($variant_json);
                $weight = $current_variant['weight']??'';
            }


            //仓库产品
            $inventory_product = [
                'spu'                      => trim($spu),
                'product_images'           => $images ? json_encode([$images['src']]):'',
                'update_time'              => date("Y-m-d H:i:s", time()),
                'created_time'             => date("Y-m-d H:i:s", time()),
                'published_time'           => date("Y-m-d H:i:s", time()),
            ];
            //seller_sku 多变体数据;
            $seller_sku_product = self::varient_seller_sku($product_insert,$inventory_product['spu'],$inventory_product['product_images'],$weight);
        try{
            Db::startTrans(); // 开启事务
            Db::name('listing_product')->insert($product_insert);
            //todo 同时将产品信息写入线下产品表; product_seller_sku表
            self::add_inventory_spu($inventory_product,$seller_sku_product,$product_variant_type);
            Db::commit(); // 提交事务
            return json(DefaultResponse(200, true, '新增成功', ''));
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            return json(DefaultResponse(200, true, $e->getMessage(), ''));
        }
    }

    /**
     * @desc    编辑产品接口
     * @date    2024-11-25
     * @author  luckyXiong
     */
    public function edit_product($params=[]){
        //验证器参数验证
        $validate    = new ProductEdit();
        $res         = $validate->check($params);
        if(!$res) return $this->jsonMessage(201, false, $validate->getError(), null);
        $id                   =  $params['id']??'';
        $spu                  =  $params['spu']??'';
        $product_variant_type =  $params['product_variant_type']??'';

        $product_title        =  $params['product_title']??'';
        $product_tags         =  $params['product_tags']??'';
        $product_desc         =  $params['product_desc']??'';

        $product_type         =  $params['product_type']??'';
        $supply_url           =  $params['supply_url']??'';
        $product_images       =  $params['product_images']??'';
        $options              =  $params['options']??'';
        $variant_json         =  $params['variant_json']??'';

        if($product_variant_type ==2 && !$variant_json){
            return  $this->jsonMessage(201,false,'产品变种类型不能为空!',null);
        }
        //主表数据写入
        $product_update = [
                'spu'                      => trim($spu),
                'product_tags'             => trim($product_tags),
                'product_title'            => trim($product_title),
                'product_desc'             => trim($product_desc),
                'product_type'             => trim($product_type),
                'supply_url'               => trim($supply_url),
                'product_images'           => $product_images ? json_encode($product_images):'',
                'options'                  => $options        ? json_encode($options):'',
                'variant_json'             => $variant_json   ? json_encode($variant_json):'',
                'update_time'              => date("Y-m-d H:i:s", time()),
            ];
        try {
            Db::startTrans(); // 开启事务
            Db::name('listing_product')->where('id',$id)->update($product_update);
            //todo 同时将产品信息写入线下产品表;
            Db::commit(); // 提交事务
            return json(DefaultResponse(200, true, '编辑成功', ''));
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            return json(DefaultResponse(200, true, $e->getMessage(), ''));
        }
    }


    /**
     * @desc    删除模版产品接口
     * @author  luckyXiong
     * @date    2024-11-28
     */
    public function delete_product($params=[]){
           $id  = $params['id']??'';
           Db::name('listing_product')->where('id',$id)->delete();
           return json(DefaultResponse(200, true, '删除成功', ''));
    }


    /**
     * @desc    多变体数据
     * @author  luckyXiong
     * @date    2024-12-06
     */
    private function varient_seller_sku($info, $spu, $image, $weight) {
        if (empty($info['variant_json'])) return '';
        // 解码 variant_json
        $variant_json = json_decode($info['variant_json'], true);
        $skuList = [];

        foreach ($variant_json as $variant) {
            $temp = get_product_sku($variant['sku'], 1);
            // 使用 explode 处理 sku
            $skuArray = strpos($temp, ',') !== false ? explode(',', $temp) : [$temp];
            $skuList = array_merge($skuList, $skuArray);  // 合并到 SKU 列表
        }

        // 获取唯一值并重置数组索引
        $uniqueSkus = array_values(array_unique($skuList));
        $currentTime = date("Y-m-d H:i:s");
        $resultList = [];

        foreach ($uniqueSkus as $sku) {
            $exist_info   = Db::name('product_seller_sku')->where(['spu'=>$spu,'seller_sku'=>$sku])->find();
            if($exist_info)  continue;
            $resultList[] = [
                'spu'          => $spu,
                'seller_sku'   => $sku,
                'image_info'   => $image,
                'weight'       => $weight,
                'created_time' => $currentTime,
                'update_time'  => $currentTime,
            ];
         }
         return $resultList;
    }

    //获取入库数据
    private function add_inventory_spu($inventory_product,$seller_sku_product,$product_variant_type){
            htmlLog(['inventory_product'=>$inventory_product,'seller_sku_product'=>$seller_sku_product,'product_variant_type'=>$product_variant_type],OPERATE_LOG . date('Ym') . '/add_inventory_spu/' . date('Ymd') . '.txt');
            $exist_product = Db::name('product')->where(['spu'=>$inventory_product['spu']])->find();
            if(!$exist_product){
                $product_id = Db::name('product')->insertGetId($inventory_product);
                //数据维护到仓库sku信息表;
                foreach($seller_sku_product as $k=>$v){
                    $seller_sku_product[$k]['product_id'] = $product_id;
                }
                Db::name('product_seller_sku')->insertAll($seller_sku_product);
            }
    }

    /**
     * @desc    获取在线产品详情接口
     * @author  luckyXiong
     * @date    2024-12-25
     */
    public function getInfo($params=[]){
         $id                     = $params['id']??'';
         $info                   = Db::name('listing_product')->where('id',$id)->find();
         $info['product_images'] = $info['product_images'] ? json_decode($info['product_images']):'';
         $info['variant_json']   = $info['variant_json']   ? json_decode($info['variant_json']):'';
         return $this->jsonMessage(200, true,'获取成功', $info);
    }


    /**
     * @desc    同步在线产品消费方法
     * @author  luckyXiong
     * @date    2024-12-27
     */
    public function copy_product_consumer($info){
        $shop_id      =  $info['shop_id']??'';
        $product_id   =  $info['product_id']??'';
        //获取当前产品的信息;
        $product_info =  Db::name('listing_product')->where('id',$product_id)->find();
        if(!$product_info)  return  true;
        $update_info  =  self::get_insert_info($product_info,$shop_id);
        Db::name('listing_shop_product')->insert($update_info);
        return true;
    }


    //获取产品信息;
    private function get_insert_info($exist_info,$shop_id){
        return  [
            'shop_id'             =>$shop_id,
            'spu'                 =>$exist_info['spu']??'',
            'product_variant_type'=>$exist_info['product_variant_type']??'',
            'product_tags'        =>$exist_info['product_tags']??'',
            'product_title'       =>$exist_info['product_title']??'',
            'product_desc'        =>$exist_info['product_desc']??'',
            'product_type'        =>$exist_info['product_type']??'',
            'supply_url'          =>$exist_info['supply_url']??'',
            'product_images'      =>$exist_info['product_images']??'',
            'options'             =>$exist_info['options']??'',
            'variant_json'        =>$exist_info['variant_json']??'',
            'create_time'         => date("Y-m-d H:i:s", time()),
            'update_time'         => date("Y-m-d H:i:s", time()),
        ];
    }



}